package com.example.demo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getCookies")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取Cookie";
    }
    @RequestMapping("/getCookies2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "从Cookie中获取值，bite:" + bite;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request, HttpServletResponse response){
        // request 中有 SessionId，可以通过 SessionId 获取 Session，如果没有 Session，就会创建一个
        HttpSession session = request.getSession();
        session.setAttribute("name", "zhangsan");
        return "设置Session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request, HttpServletResponse response){
        // request 中有 SessionId，可以通过 SessionId 获取 Session
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从Session获取name:" + name;
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        // request 中有 SessionId，可以通过 SessionId 获取 Session
        String name = (String) session.getAttribute("name");
        return "从Session获取name:" + name;
    }
    @RequestMapping("/getSession3")
    public String getSession2(@SessionAttribute("name") String name){
        // request 中有 SessionId，可以通过 SessionId 获取 Session
        return "从Session获取name:" + name;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request, HttpServletResponse response){
        String userAgent = request.getHeader("User-Agent");
        return "从Header中获取信息：User-Agent:" + userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader(@RequestHeader("User-Agent") String userAgent){
        return "从Header中获取信息：User-Agent:" + userAgent;
    }
}
